package com.neusoft.feature;

import org.junit.Test;

/**
 * @author lichunlong lcl253137@alibaba-inc.com
 * @desc switch表达式
 * @date 2023-01-05
 */
public class SwitchFeature {

    /**
     * JDK 12以前: 必须要在case语法中以break结尾，否则会造成穿透
     */
    @Test
    public void test1() {
        int numberOfLetters;
        Fruit fruit = Fruit.APPLE;
        switch (fruit) {
            case PEAR:
                numberOfLetters = 1;
                break;
            case APPLE:
            case GRAPE:
            case MANGO:
                numberOfLetters = 2;
                break;
            case ORANGE:
            case PAPAYA:
                numberOfLetters = 3;
                break;
            default:
                throw new IllegalStateException("No Such Fruit:" + fruit);
        }
        System.out.println(numberOfLetters);
    }

    /**
     * JDK 12: Switch表达式的写法，省去了break语句，避免了因少写break而出错
     */
    @Test
    public void test2() {
        Fruit fruit = Fruit.GRAPE;
        switch (fruit) {
            case PEAR -> System.out.println(4);
            case APPLE, MANGO, GRAPE -> System.out.println(5);
            case ORANGE, PAPAYA -> System.out.println(6);
            default -> throw new IllegalStateException("No Such Fruit:" + fruit);
        }
    }

    /**
     * JDK 12: Switch表达式可以直接添加返回值，不再是只能在switch中处理逻辑
     */
    @Test
    public void test3() {
        Fruit fruit = Fruit.GRAPE;
        int numberOfLetters = switch (fruit) {
            case PEAR -> 4;
            case APPLE, MANGO, GRAPE -> 5;
            case ORANGE, PAPAYA -> 6;
            default -> throw new IllegalStateException("No Such Fruit:" + fruit);
        };
        System.out.println(numberOfLetters);
    }

    /**
     * JDK 13: 引入了yield语句，用于返回值
     */
    @Test
    public void test4() {
        String x = "2";
        int i = switch (x) {
            case "1":
                yield 1;
            case "2":
                yield 2;
            default:
                yield 3;
        };
        System.out.println(i);
    }

    enum Fruit {
        PEAR, APPLE, GRAPE, MANGO, ORANGE, PAPAYA;
    }
}
